package com.noisyair.android.alvin.apps.sms;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.Phones;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;

import com.noisyair.android.alvin.activities.AlvinListActivity;

public class ViewMessagesActivity extends AlvinListActivity {

	private ArrayList<TextMessage> messages;
	private MessageAdapter mAdapter;

	Uri mInboxURI = Uri.parse("content://sms/inbox");

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		registerForContextMenu(getListView());
		
		// Create a list of custom message objects, each is a text message
		// with body, name and date.
		messages = new ArrayList<TextMessage>();

		// This section is a bit complex. We need two cursors, because we have
		// to
		// query two databases at the same time. ONe is the SMS content to get
		// the text
		// message body and date, the other is the Person content to get the
		// actual name
		// of the contact who sent the text. For every text message, we look up
		// the Person associated
		// with the unique id.
		
		Cursor C = getContentResolver().query(mInboxURI, null, null, null,
				"date DESC");

		if (C.moveToFirst()) {
			int nameCol = C.getColumnIndex("person"); // This column is an ID,
														// not a real name
			int dateCol = C.getColumnIndex("date");
			int bodyCol = C.getColumnIndex("body");
			int readCol = C.getColumnIndex("read");

			do {
				TextMessage textmessage = new TextMessage();
				textmessage.setDate(C.getLong(dateCol));
				textmessage.setMMessage(C.getString(bodyCol));
				textmessage.wasRead(C.getString(readCol));
				textmessage.setNameID(C.getString(nameCol));
				textmessage.setMessageID(C.getString(C.getColumnIndex("_id")));
				textmessage.setMessageThreadID(C.getString(C.getColumnIndex("thread_id")));

				// here is where we do the lookup in the other DB to find the
				// actual name
				// associated with the person ID we retrieved above.
				Cursor phoneCursor = getContentResolver().query(
						Contacts.Phones.CONTENT_URI,
						null,
						Contacts.Phones.PERSON_ID + " = "
								+ textmessage.getNameID(), null, null);
				if (phoneCursor.moveToFirst()) {
					textmessage.setMName(phoneCursor.getString(phoneCursor
							.getColumnIndex(Phones.NAME)));
					textmessage.setNumber(phoneCursor.getString(phoneCursor
							.getColumnIndex(Phones.NUMBER)));
				}
				phoneCursor.close();
				messages.add(textmessage);
			} while (C.moveToNext());
		}
		C.close();

		// Bind the data to the view:
		mAdapter = new MessageAdapter(this, R.layout.viewmessageswindow,
				messages);
		setListAdapter(mAdapter);
	}

	// Creation of the context menus:
	
	/*
	 * The current version of the SDK doesn't seem to allow
	 * for the customization, subclassing of MenuItem objects.
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.viewmessagescontextmenu, menu);
	    

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		/*
		 * How do we match the menu ID's in this case?
		 */
		String itemTitle = item.getTitle().toString();
		
		if(itemTitle.equals("Reply")){
			Log.i("Alvin", "reply menu was selected");
			Intent i = new Intent(ViewMessagesActivity.this, SendSMSActivity.class);		
			TextMessage t = messages.get(getListView().getSelectedItemPosition());
			i.putExtra("name", t.getMName());
			i.putExtra("number", t.getNumber());
			i.putExtra("message", "");
			this.startActivity(i);
			return true;
		}
		else if(itemTitle.equals("Delete Thread")){
			TextMessage t = messages.get(getListView().getSelectedItemPosition());		
			getContentResolver().delete(Uri.parse("content://sms/conversations/" + t.getMessageThreadID()),null,null);	
			getListView().getSelectedView().setVisibility(View.GONE);
			return true;
		}
		
		else if(itemTitle.equals("Mark As Read / Unread")){
			TextMessage t = messages.get(getListView().getSelectedItemPosition());
			if(t.wasRead()){
				t.wasRead(false);
				getListView().getSelectedView().findViewById(R.id.messageperson).setBackgroundColor(0x55BBBBBB);
				getListView().getSelectedView().findViewById(R.id.messagedate).setBackgroundColor(0x55BBBBBB);
				getListView().getSelectedView().findViewById(R.id.messagebody).setBackgroundColor(0x55BBBBBB);
				ContentValues values = new ContentValues();
				values.put("read", "0");
				String where  = "_id = "+ t.getMessageID();
				getContentResolver().update(mInboxURI, values, where, null);
			}
			else{
				t.wasRead(true);		
				getListView().getSelectedView().findViewById(R.id.messageperson).setBackgroundColor(0x00000000);
				getListView().getSelectedView().findViewById(R.id.messagedate).setBackgroundColor(0x00000000);
				getListView().getSelectedView().findViewById(R.id.messagebody).setBackgroundColor(0x00000000);
				ContentValues values = new ContentValues();
				values.put("read", "1");
				String where  = "_id = "+ t.getMessageID();
				getContentResolver().update(mInboxURI, values, where, null);
			}
			return true;
		}
		else{
			Log.i("Alvin", "nothing matched");
			return super.onContextItemSelected(item);
		}
	}

	/* Creates the menu items */
	private static final int CREATE_SMS_MENU_ID = 100843;

    
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, CREATE_SMS_MENU_ID, 0, "Create new message");
		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CREATE_SMS_MENU_ID:
			Intent i = new Intent(ViewMessagesActivity.this, SendSMSActivity.class);
            startActivity(i);
            return true;
		}
		return false;
	}
}
